import Link from 'next/link';
import { useRouter } from "next/router";
import { useState, useEffect } from "react";
import { Popover, Empty, message } from 'antd';
import { getID } from '@/utils';
import moment from 'moment';
import Cookies from 'js-cookie';
// css
import styles from '@/styles/CommonDetail.module.scss';
import couponStyles from "@/styles/CommonPersonal.module.scss";
// api
import { getCouponByGoodsID, receiveCoupon } from '@/api/coupon';
// component
import CouponItem from '@/pages_components/components/CouponItem';

// 优惠券列表
const CouponList = ({ list, receiveCouponFn }) => {
    
    const token = Cookies.get('token'),
          userInfo = JSON.parse(Cookies.get('userInfo') || "{}");
    const desc = (token && userInfo?.id) ? "持续关注我们，领券机会多多~" : "请登录后，查看优惠券详情~";

    return <div className={[couponStyles['coupon-content'], couponStyles['popover']].join(' ')}>
        <h3>优惠券</h3>
        {
            !list.length
            ? <div className={styles['empty']}>
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={desc} />   
              </div>
            : list.map(item => {
                return <CouponItem data={item} receiveCouponFn={receiveCouponFn} key={item.id} />
            })
        }
    </div>
}

// 活动/优惠券
const Coupon = ({ coupons: { couponDTOList, activityRuleDTOList } }) => {

    const router = useRouter();
    const { query: { path }, asPath } = router;
    const [activity, setActivity] = useState([]);
    const [list, setList] = useState([]);

    useEffect(() => {

        couponDTOList.length && getCoupons();

        // 数据处理
        const _activity = [];
        activityRuleDTOList.forEach(item => {
            const { tagName, activityBaseId, ruleTitle, startTime, endTime } = item;
            const findIdx = _activity.findIndex(fItem => {
                return fItem.tagName == tagName && fItem.activityBaseId == activityBaseId
            });
            if(findIdx < 0){
                _activity.push({
                    tagName,
                    activityBaseId,
                    ruleTitles: [ruleTitle],
                    startTime,
                    endTime
                })
            }else{
                _activity[findIdx]?.ruleTitles?.push(ruleTitle);
            }
        });

        setActivity([..._activity]);
        
    }, []);

    // 获取优惠券
    function getCoupons (){
        const id = getID(path);
        getCouponByGoodsID({
            goodsId: id
        }).then(res => {
            const { code, data } = res;
            if(code === 0 && data && data.length){
                const _data = data.map(item => {
                    const dto = item.couponDetailAppDTO,
                        dto_3 = dto.couponCashRuleDetailAppDTO,
                        dto_2 = dto.couponFullReduceRuleDetailAppDTO,
                        dto_1 = dto.couponExperienceRuleDetailAppDTO;
                    const name = dto.name,
                        remark = dto.remark,
                        couponType = dto.couponType,
                        rebatePrice = dto_2?.rebatePrice || dto_3?.rebatePrice,
                        satisfyPrice = dto_2?.satisfyPrice || '',
                        startTime = dto_2?.startTime || '',
                        endTime = dto_2?.endTime || '',
                        validityDay = dto_1?.validityDay || dto_3?.validityDay;
                    return {
                        ...item,
                        name,
                        remark,
                        couponType,
                        rebatePrice,
                        satisfyPrice,
                        startTime,
                        endTime,
                        validityDay,
                    }
                });
                setList([..._data])
            }
        })
    }
    // 领取 
    function receiveCouponFn (item){
        receiveCoupon({
            ids: [item.id]
        }).then(res => {
            const { code } = res;
            if(code == 0){
                message.success('已领取');
                getCoupons();
            }
        })
    }
    
    return (
        <div className={styles['coupon-box']}>
            {
               couponDTOList.length || activityRuleDTOList.length ?
                <>
                    <div className={styles['list']}>
                        <div className={styles['activity']}>
                            {/* <h5>优惠活动/券：</h5> */}
                            {
                                activity.map((item, idx) => {
                                    const { ruleTitles, startTime, endTime } = item;
                                    return <p key={idx}>
                                                <Link href={`/activity/${item.activityBaseId}?from=${encodeURIComponent(asPath)}`}>
                                                    <a target="_blank">
                                                        <i>{item.tagName}</i>
                                                        {
                                                            ruleTitles.map(r => <span key={r} title={r}>{r}</span>)
                                                        }
                                                    </a>
                                                </Link>
                                                <em>活动时间：{moment(startTime).format('YYYY.MM.DD')} - {moment(endTime).format('YYYY.MM.DD')}</em>
                                            </p>
                                })
                            }
                        </div>
                        {
                            couponDTOList.length 
                            ? <div className={styles['coupon']}>
                                <strong>优惠券：</strong>
                                {
                                    couponDTOList.map((item, index) => <span key={index}>{item.couponName}</span>)
                                }
                                <Popover 
                                    placement="bottomRight"
                                    trigger="click"
                                    content={
                                        <div className={styles['coupons-popover']}><CouponList list={list} receiveCouponFn={receiveCouponFn} /></div>
                                    }
                                ><em>查看详情</em></Popover>
                            </div>
                            : ""
                        }
                    </div>
                </> : ''
            }
        </div>
    )
}

export default Coupon